from src.components.mongodb_handler import MongodbHandler as MongodbHandler
from src.components.redis_handler import RedisHandler
from src.config.mongodb_config import MongodbConfig as MongodbConfig


class PreLoader:
    """
    服务启动时的预先加载类
    """

    @staticmethod
    def store_api_info_in_redis():
        """
        从Mongodb的api_info集合中获取数据，以url为key、description为value，存储在redis中，并且永不过期
        :return:
        """
        # 连接数据库
        database = MongodbHandler.get_db(MongodbConfig.IP, MongodbConfig.PORT, MongodbConfig.DATABASE)

        # 连接redis
        RedisHandler.create_client()

        # 将api_info集合中的数据存储在redis中
        api_info_collection = database.api_info
        api_info_cursor = api_info_collection.find()
        for api_info_dict in api_info_cursor:
            RedisHandler.set_forever(api_info_dict['url'], api_info_dict['description'])

        RedisHandler.close()
        MongodbHandler.close()

    @staticmethod
    def store_page_info_in_redis():
        """
        从Mongodb的page_info集合中获取数据，以path为key、name为value，存储在redis中，并且永不过期
        :return:
        """
        # 连接数据库
        database = MongodbHandler.get_db(MongodbConfig.IP, MongodbConfig.PORT, MongodbConfig.DATABASE)

        # 连接redis
        RedisHandler.create_client()

        # 将page_info集合中的数据存储在redis中
        page_info_collection = database.page_info
        page_info_cursor = page_info_collection.find()
        for page_info_dict in page_info_cursor:
            RedisHandler.set_forever(page_info_dict['path'], page_info_dict['name'])

        RedisHandler.close()
        MongodbHandler.close()
